package com.jy.appmarket.activity;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.jy.app.market.apk.type.CommentType;
import com.jy.appmarket.R;
import com.jy.appmarket.dialog.WaitDialog;
import com.jy.appmarket.network.engine.BaseNetEngine;
import com.jy.appmarket.network.engine.SubmitCommentEngine;
import com.jy.appmarket.network.engine.cachestrategy.CacheStrategy;
import com.jy.appmarket.network.resultdata.SimpleBaseResult;
import com.jy.appmarket.network.task.NetTask;
import com.jy.appmarket.network.task.NetTask.NetTaskListener;

/**
 * @author xinhui.cheng
 *
 */
public class SubmitCommentActivity extends Activity implements NetTaskListener,
		View.OnClickListener {

	// private static final String TAG = "SubmitCommentActivity";
	public static final String EXTRA_PKG = "submit_comment_pkg";
	public static final String EXTRA_VERSIONCODE = "submit_comment_vc";
	public static final String EXTRA_COMMENTED = "submit_comment_commented";

	private static final int COMMENT_LIMIT = 200;

	private EditText mContent;
	private TextView mWords;
	private Button mButton;

	private String mPkgName;
	private int mVersionCode;
	private String mEval = CommentType.EMPTY.name();
	private NetTask mNetTask;

	private WaitDialog mWaitDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.submit_comment_layout);
		getExtras();
		mContent = findViewById(R.id.comment_content);
		mWords = findViewById(R.id.current_words);
		findViewById(R.id.dialog_button1).setOnClickListener(this);
		mButton = findViewById(R.id.dialog_button2);
		mButton.setOnClickListener(this);
		RadioGroup group = findViewById(R.id.evaluate_group);
		group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				mEval = (checkedId == R.id.dislike) ? "BAD" : "GOOD";
			}
		});

		mContent.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// nothing todo
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// nothing todo
			}

			@Override
			public void afterTextChanged(Editable s) {
				final int length = s.length();
				if (length > COMMENT_LIMIT) {
					mWords.setTextColor(Color.RED);
					mButton.setEnabled(false);
				} else {
					mWords.setTextColor(Color.GRAY);
					mButton.setEnabled(true);
				}

				mWords.setText(length + "/" + COMMENT_LIMIT);
			}
		});
	}

	private void getExtras() {
		if (getIntent() == null) {
			finish();
		}

		mPkgName = getIntent().getStringExtra(EXTRA_PKG);
		mVersionCode = getIntent().getIntExtra(EXTRA_VERSIONCODE, 0);
		if (TextUtils.isEmpty(mPkgName)) {
			Toast.makeText(this, "暂时无法评论这个应用", Toast.LENGTH_SHORT).show();
			finish();
		}
	}

	@Override
	public void onTaskRunSuccessful(int tag, BaseNetEngine engine) {
		dismissWaitDialog();
		SimpleBaseResult result = (SimpleBaseResult) engine.getResultData();
		if (!result.isOK()) {
			String text = "评论失败了";
			if (!TextUtils.isEmpty(result.getMessage())) {
				text = result.getMessage();
			}
			Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(this, "评论成功", Toast.LENGTH_SHORT).show();
			setResult(RESULT_OK);
			finish();
		}

	}

	@Override
	public void onTaskRunError(int tag) {
		dismissWaitDialog();
		Toast.makeText(this, "评论失败了", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onTaskRunCanceled(int tag) {
		// nothing todo
	}

	private boolean isValidContent(String content) {
        return !content.matches("\\s+") && !content.matches("[0-9]*");
    }

	private void submitComment() {
		final String content = mContent.getText().toString().trim();
		if (content.isEmpty()) {
			Toast.makeText(this, "请填写评论", Toast.LENGTH_SHORT).show();
			return;
		}
		if (content.length() < 5) {
			Toast.makeText(this, "请评论至少5个字", Toast.LENGTH_SHORT).show();
			return;
		}
		if (content.length() > COMMENT_LIMIT) {
			Toast.makeText(this, "评论超过了" + COMMENT_LIMIT + "字，请删减", Toast.LENGTH_SHORT).show();
			return;
		}
		if (!isValidContent(content)) {
			Toast.makeText(this, "请认真评论", Toast.LENGTH_SHORT).show();
			return;
		}
		showWaitDialog();
		SubmitCommentEngine engine = new SubmitCommentEngine(mPkgName, mEval, content, mVersionCode);
		engine.setCacheStrategy(new CacheStrategy(false));
		mNetTask = new NetTask(this, engine, 0);
		mNetTask.setListener(this);
		new Thread(mNetTask).start();
	}

	private void showWaitDialog() {
		if (mWaitDialog == null) {
			mWaitDialog = new WaitDialog(this);
			mWaitDialog.setCanceledOnTouchOutside(false);
			mWaitDialog.setCancelable(false);
		}
		if (mWaitDialog.isShowing()) {
			return;
		}
		mWaitDialog.showTitle("请稍候...").show();
	}

	private void dismissWaitDialog() {
		if (mWaitDialog != null) {
			mWaitDialog.dismiss();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.dialog_button1:
			setResult(Activity.RESULT_CANCELED);
			finish();
			break;
		case R.id.dialog_button2: {
			submitComment();
		}
			break;
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mNetTask != null) {
			mNetTask.cancel();
			mNetTask.setListener(null);
			mNetTask = null;
		}
	}
}
